package com.chhuang.mongo.core.controller;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.data.mongodb.core.query.Criteria;

import com.chhuang.mongo.core.dao.AbstractMongoDao;

public class AbstractController {

	/**
	 * 从request中获取客户端ip
	 * 
	 * @param request
	 * @return
	 */
    protected String getRemoteHost(HttpServletRequest request){
	    String ip = request.getHeader("x-forwarded-for");
	    String unknown = "unknown";
	    if(StringUtils.isBlank(ip) || unknown.equalsIgnoreCase(ip)){
	        ip = request.getHeader("Proxy-Client-IP");
	    }
	    if(StringUtils.isBlank(ip) || unknown.equalsIgnoreCase(ip)){
	        ip = request.getHeader("WL-Proxy-Client-IP");
	    }
	    if(StringUtils.isBlank(ip) || unknown.equalsIgnoreCase(ip)){
	        ip = request.getRemoteAddr();
	    }
	    return ip.equals("0:0:0:0:0:0:0:1")?"127.0.0.1":ip;
	}
    
    /**
     * 获取request中的cookie
     * 
     * @param request
     * @param name
     * @param value
     * @return
     */
    protected String getCookie(HttpServletRequest request, String name){
    	String result = null;
    	Cookie[] cookies = request.getCookies();
    	if(cookies!=null && cookies.length>0){
    		for(Cookie cookie : cookies){
    			if(name.equalsIgnoreCase(cookie.getName())){
    				result = cookie.getValue();
    				break;
    			}
    		}
    	}
    	return result;
    }
    
	/**
	 * 拼接查询条件
	 * 
	 * @param criteria
	 * @param column
	 * @param value
	 * @return
	 */
	protected Criteria getSearchCriteria(String column, String value){
		if(StringUtils.isNotBlank(value)){
			//模糊匹配，忽略大小写
			return Criteria.where(column).regex(AbstractMongoDao.LIKE.replaceFirst(AbstractMongoDao.KEY, value), AbstractMongoDao.IGNORE_CASE);
		}
		return null;
	}
	
}
